<template>
  <div class="module-container">
    <CreateAccount 
      :visible="showCreateDialog"
      @update:visible="showCreateDialog = $event"
      @success="handleCreateSuccess"
    />
    
    <EditAccount 
      ref="editAccountRef"
      :visible="showEditDialog"
      @update:visible="showEditDialog = $event"
      @success="handleEditSuccess"
    />
    
    <h2>账户信息</h2>
    <div class="module-content">
      <div class="search-container">
        <div class="search-box">
          <input 
            type="text" 
            v-model="searchQuery" 
            placeholder="请输入手机号"
            class="search-input"
            @keyup.enter="handleSearch"
          />
          <button @click="handleSearch" class="search-button">搜索</button>
          <button @click="handleCreate" class="create-button">
            创建账户
          </button>
          <button 
            v-if="selectedAccounts.length > 0"
            @click="handleBatchDelete"
            class="batch-delete-button"
          >
            批量删除 ({{ selectedAccounts.length }})
          </button>
        </div>
      </div>
      
      <div class="table-container">
        <table class="data-table">
          <thead>
            <tr>
              <th>
                <input 
                  type="checkbox" 
                  :checked="areAllAccountsSelected" 
                  @change="toggleSelectAll"
                />
              </th>
              <th>手机号(主键)</th>
              <th>预存费用</th>
              <th>总消费</th>
              <th>月消费</th>
              <th>是否欠费</th>
              <th>欠费金额</th>
              <th>创建时间</th>
              <th>更新时间</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="account in paginatedAccounts" :key="account.phone">
              <td>
                <input 
                  type="checkbox" 
                  :checked="selectedAccounts.includes(account.id)"
                  @change="toggleAccountSelection(account.id)"
                />
              </td>
              <td>{{ account.phone }}</td>
              <td>{{ account.preDeposit }}</td>
              <td>{{ account.totalConsumption }}</td>
              <td>{{ account.monthConsumption }}</td>
              <td>{{ account.isArrears ? '是' : '否' }}</td>
              <td>{{ account.arrearsAmount }}</td>
              <td>{{ formatDate(account.createTime) }}</td>
              <td>{{ formatDate(account.updateTime) }}</td>
              <td>
                <button class="action-button view">查看</button>
                <button class="action-button edit" @click="handleEdit(account)">编辑</button>
                <button class="action-button delete" @click="handleDelete(account)">删除</button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
      
      <div class="pagination">
        <button 
          class="pagination-button" 
          :disabled="pagination.current <= 1"
          @click="prevPage"
        >
          上一页
        </button>
        <span class="pagination-info">第 {{ pagination.current }} 页，共 {{ totalPages }} 页</span>
        <button 
          class="pagination-button" 
          :disabled="pagination.current >= totalPages"
          @click="nextPage"
        >
          下一页
        </button>
      </div>
    </div>
  </div>
</template>

<script>
import CreateAccount from './CreateAccount.vue'
import EditAccount from './EditAccount.vue'
import { getAccountInfo, deleteAccountInfo, deleteBatchAccountInfo } from '@/apis/account'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: 'AccountInfoTemplate',
  components: {
    CreateAccount,
    EditAccount
  },
  data() {
    return {
      allAccounts: [],
      loading: false,
      searchQuery: '',
      showCreateDialog: false,
      showEditDialog: false,
      currentEditAccount: null,
      selectedAccounts: [], // 存储选中的账户ID
      pagination: {
        current: 1,
        pageSize: 10,
        total: 0
      }
    }
  },
  computed: {
    totalPages() {
      return Math.ceil((this.pagination.total || 0) / (this.pagination.pageSize || 10));
    },
    // 分页后的账户数据
    paginatedAccounts() {
      const start = (this.pagination.current - 1) * this.pagination.pageSize;
      const end = start + this.pagination.pageSize;
      return this.filteredAccounts.slice(start, end);
    },
    // 根据搜索条件过滤后的账户数据
    filteredAccounts() {
      let filtered = this.allAccounts;
      
      // 如果有搜索查询，按搜索结果筛选
      if (this.searchQuery.trim()) {
        const query = this.searchQuery.trim().toLowerCase();
        filtered = filtered.filter(account => 
          (account.phone && account.phone.toLowerCase().includes(query))
        );
      }
      
      return filtered;
    },
    // 检查是否所有账户都被选中
    areAllAccountsSelected() {
      return this.paginatedAccounts.length > 0 && 
             this.selectedAccounts.length === this.paginatedAccounts.length;
    }
  },
  methods: {
    async loadAccountData() {
      this.loading = true;
      try {
        const res = await getAccountInfo({
          offset: (this.pagination.current - 1) * this.pagination.pageSize,
          limit: this.pagination.pageSize
        });
        console.log('账户数据:', res);
        // 根据后端接口返回的数据结构处理数据
        if (res && res.code === 0 && res.data) {
          // 使用后端返回的 records 数据
          this.allAccounts = res.data.records || [];
          this.pagination.total = res.data.total || 0;
        }
      } catch (error) {
        console.error('获取账户数据失败:', error);
        // 出错时清空数据
        this.allAccounts = [];
      } finally {
        this.loading = false;
        // 数据加载完成后清除选中项
        this.selectedAccounts = [];
      }
    },
    handleSearch() {
      console.log('搜索账户:', this.searchQuery);
      // 重置到第一页并重新加载数据
      this.pagination.current = 1;
      this.loadAccountData();
    },
    handleCreate() {
      this.showCreateDialog = true;
    },
    handleCreateSuccess() {
      // 创建成功后重新加载数据
      this.loadAccountData();
    },
    handleEdit(account) {
      this.currentEditAccount = account;
      this.$nextTick(() => {
        this.$refs.editAccountRef.setFormData(account);
        this.showEditDialog = true;
      });
    },
    handleEditSuccess() {
      // 编辑成功后重新加载数据
      this.loadAccountData();
      this.currentEditAccount = null;
    },
    handleDelete(account) {
      ElMessageBox.confirm(
        `确定要删除账户 ${account.phone} 吗？`,
        '确认删除',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).then(async () => {
        try {
          const res = await deleteAccountInfo(account.id);
          if (res && res.code === 0) {
            ElMessage.success('删除成功');
            this.loadAccountData();
          } else {
            ElMessage.error(res?.msg || '删除失败');
          }
        } catch (error) {
          console.error('删除账户失败:', error);
          ElMessage.error('删除账户失败');
        }
      }).catch(() => {
        // 用户取消删除
        ElMessage.info('已取消删除');
      });
    },
    // 切换账户选择状态
    toggleAccountSelection(accountId) {
      const index = this.selectedAccounts.indexOf(accountId);
      if (index > -1) {
        // 如果已选中，则取消选中
        this.selectedAccounts.splice(index, 1);
      } else {
        // 如果未选中，则添加到选中列表
        this.selectedAccounts.push(accountId);
      }
    },
    // 切换全选状态
    toggleSelectAll(event) {
      if (event.target.checked) {
        // 全选当前页的所有账户
        this.selectedAccounts = this.paginatedAccounts.map(account => account.id);
      } else {
        // 取消全选
        this.selectedAccounts = [];
      }
    },
    // 处理批量删除
    handleBatchDelete() {
      if (this.selectedAccounts.length === 0) {
        ElMessage.warning('请先选择要删除的账户');
        return;
      }
      
      ElMessageBox.confirm(
        `确定要删除选中的 ${this.selectedAccounts.length} 个账户吗？`,
        '确认批量删除',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).then(async () => {
        try {
          // 将选中的ID数组转换为逗号分隔的字符串
          const idsString = this.selectedAccounts.join(',');
          const res = await deleteBatchAccountInfo(idsString);
          if (res && res.code === 0) {
            ElMessage.success('批量删除成功');
            this.loadAccountData();
          } else {
            ElMessage.error(res?.msg || '批量删除失败');
          }
        } catch (error) {
          console.error('批量删除账户失败:', error);
          ElMessage.error('批量删除账户失败');
        }
      }).catch(() => {
        // 用户取消删除
        ElMessage.info('已取消批量删除');
      });
    },
    formatDate(dateString) {
      if (!dateString) return '-';
      const date = new Date(dateString);
      return isNaN(date.getTime()) ? '-' : date.toLocaleString();
    },
    prevPage() {
      if (this.pagination.current > 1) {
        this.pagination.current--;
        this.loadAccountData();
      }
    },
    nextPage() {
      if (this.pagination.current < this.totalPages) {
        this.pagination.current++;
        this.loadAccountData();
      }
    }
  },
  mounted() {
    this.loadAccountData();
  }
}
</script>

<style scoped>
@import '../../assets/global-module-styles.css';

.search-box {
  display: flex;
  gap: 10px;
  align-items: center;
  flex-wrap: wrap;
}

.create-button {
  padding: 10px 20px;
  background-color: #28a745;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
  align-self: center;
  white-space: nowrap;
}

.create-button:hover {
  background-color: #218838;
}

.batch-delete-button {
  padding: 10px 20px;
  background-color: #dc3545;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
  align-self: center;
  white-space: nowrap;
}

.batch-delete-button:hover {
  background-color: #c82333;
}

.pagination-button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}
</style>